package com.taomus.mytools.lang.jython;

import java.io.InputStream;

import org.python.util.PythonInterpreter;

import com.taomus.mytools.helper.stream.StreamHelper;
import com.taomus.mytools.lang.ILanguageHelper;
import com.taomus.mytools.lang.IMethod;

public class JythonHelper extends ILanguageHelper{
	
	private PythonInterpreter pi = new PythonInterpreter();

	public JythonHelper(){
		pi.exec("import sys");
		this.setClassPath("com.cn.mrc.mytools.fw4cache");
	}
	
	public JythonHelper(String classpath){
		pi.exec("import sys");
		this.setClassPath("com.cn.mrc.mytools.fw4cache");
		this.setClassPath(classpath);
	}
	
	@Override
	public void putPath(String name, String path) {
		if(!this.filePool.containsKey(name)){
			this.filePool.put(name, path);
		}
	}

	@Override
	public IMethod newInstance(String name) throws Exception {
		String path = null;
		if(name.endsWith(".py")){
			path = name;
			name = name.substring(name.lastIndexOf("/")+1);
			name = name.replace(".py", "");
		}else{
			path = this.filePool.get(name);
		}
		InputStream input = StreamHelper.getInputStreamByFileName(path);
		pi.execfile(input);
		pi.exec("pyinstance = "+name+"()");
		return new JythonMethod(pi);
	}

	@Override
	public Class<?> getClass(String name) throws Exception {
		return null;
	}
	
	@Override
	public void setClassPath(String classpath) {
		pi.exec("sys.path.append('__pyclasspath__/"+classpath+"')");
	}

}
